package com.jstyle.jclife.activity;

import android.Manifest;

import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.NotifyDataAdapter;
import com.jstyle.jclife.daoManager.NotifyDataDaoManager;
import com.jstyle.jclife.model.NotifyData;
import com.jstyle.jclife.utils.PermissionsUtil;
import com.jstyle.jclife.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 提醒开关设置
 */
public class NotifySettingActivity extends BaseActivity {

    @BindView(R.id.bt_goal_back)
    Button btGoalBack;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_share)
    ImageView ivShare;
    @BindView(R.id.RecyclerView_notify)
    RecyclerView RecyclerViewNotify;
    @BindArray(R.array.notify_array)
    String[] notifyArray;
    @BindArray(R.array.notify_array_listener)
    String[] notifyArrayListener;
    @BindView(R.id.button_notify_name)
    TextView buttonNotifyName;
    @BindView(R.id.switch_notify_all)
    SwitchCompat switchNotifyAll;
    @BindView(R.id.text_item_other)
    TextView textItemOther;
    private List<NotifyData> notifyDataList;
    private NotifyDataAdapter notifyDataAdapter;
    private static final String ENABLED_NOTIFICATION_LISTENERS = "enabled_notification_listeners";
    private static final String ACTION_NOTIFICATION_LISTENER_SETTINGS = "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_notify_setting);
        ButterKnife.bind(this);
        requestPermissions();
        initData();
        init();
    }

    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            PermissionsUtil.requestPermissions(this, null,Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.CALL_PHONE, Manifest.permission.ANSWER_PHONE_CALLS,Manifest.permission.READ_CALL_LOG);
        }else{
            PermissionsUtil.requestPermissions(this, null,Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.CALL_PHONE,Manifest.permission.READ_CALL_LOG);
        }

    }

    private void initData() {
        notifyDataList = new ArrayList<>();
        for (int i=0;i<notifyArray.length;i++) {
//            String notifyName=notifyArray[i];
            notifyDataList.add(getNotifyData(i));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(!isEnabled())switchNotifyAll.setChecked(false);
    }

    private NotifyData getNotifyData(int position){
        NotifyData notifyData = NotifyDataDaoManager.getNotifyData(position);
        return  notifyData;
    }
    private void init() {

        final NotifyData notifyData=getNotifyData(99);
        ScreenUtils.setSwitchColor(switchNotifyAll);
        switchNotifyAll.setChecked(notifyData.getEnable());
        switchNotifyAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked&&!isEnabled()){
                   showConfirmDialog();
                }
                notifyData.setEnable(isChecked);
                NotifyDataDaoManager.updateNotifyData(notifyData);
                updateNotify(isChecked);
            }
        });
        btGoalBack.setText(R.string.Message);
        ScreenUtils.setTitleTypeface(btGoalBack);
        ivShare.setVisibility(View.GONE);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        notifyDataAdapter = new NotifyDataAdapter(notifyDataList);

        RecyclerViewNotify.setAdapter(notifyDataAdapter);
        RecyclerViewNotify.setLayoutManager(linearLayoutManager);
    }

    private void updateNotify(boolean enable){
        List<NotifyData>notifyDataList=new ArrayList<>();
        for (int i=0;i<notifyArray.length;i++) {
            NotifyData notifyData=getNotifyData(i);
            notifyData.setEnable(enable);
            notifyDataList.add(notifyData);
            NotifyDataDaoManager.updateNotifyData(notifyData);
        }
        notifyDataAdapter.updateDate(notifyDataList);
    }
    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        finish();
    }
    private boolean isEnabled() {
        String pkgName = getPackageName();
        final String flat = Settings.Secure.getString(getContentResolver(), ENABLED_NOTIFICATION_LISTENERS);
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (int i = 0; i < names.length; i++) {
                final ComponentName cn = ComponentName.unflattenFromString(names[i]);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    private void showConfirmDialog() {
        new AlertDialog.Builder(this,R.style.appalertdialog)
                .setMessage(getString(R.string.enable_notifcation_tips))
                .setTitle(getString(R.string.enable_notify_title))
                .setIconAttribute(android.R.attr.alertDialogIcon)
                .setCancelable(true)
                .setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                openNotificationAccess();
                            }
                        })
                .setNegativeButton(android.R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // do nothing
                                switchNotifyAll.setChecked(false);
                            }
                        })
                .setCancelable(false).create().show();
    }
    private void openNotificationAccess() {
        startActivity(new Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS));
    }
}
